package cn.kuporo.seckill.user.application.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.kuporo.seckill.common.exception.ErrorCode;
import cn.kuporo.seckill.common.exception.SeckillException;
import cn.kuporo.seckill.common.model.response.Response;
import cn.kuporo.seckill.common.model.vo.UserAddReqVO;
import cn.kuporo.seckill.user.application.service.SeckillUserService;
import cn.kuporo.seckill.user.domain.model.SeckillUser;
import cn.kuporo.seckill.user.domain.repository.SeckillUserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


/**
 * @author: kuporo
 * @since: 2025/7/7
 * @description:
 */
@Service
@RequiredArgsConstructor
public class SeckillUserServiceImpl implements SeckillUserService {
    private final PasswordEncoder passwordEncoder;
    private final SeckillUserRepository seckillUserRepository;

    @Override
    public Response<String> login(UserAddReqVO userAddReqVO) {
        String userName = userAddReqVO.getUserName();
        String password = userAddReqVO.getPassword();
        SeckillUser seckillUser = seckillUserRepository.getSeckillUserByUserName(userName);
        if (seckillUser == null){
            throw new SeckillException(ErrorCode.USERNAME_IS_ERROR);
        }
        String encodePassword = seckillUser.getPassword();
        boolean isMatch = passwordEncoder.matches(password, encodePassword);
        if (!isMatch){
            throw new SeckillException(ErrorCode.PASSWORD_IS_ERROR);
        }
        StpUtil.login(seckillUser.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return Response.success(tokenInfo.tokenValue);
    }

    @Override
    public Response<SeckillUser> queryUserInfo() {
        long userId = StpUtil.getLoginIdAsLong();
        SeckillUser seckillUser = seckillUserRepository.queryUserInfo(userId);
        seckillUser.setPassword(null);
        return Response.success(seckillUser);
    }

}
